/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include <string.h>

// this should be enough
static char buf[65536] = {};
static char code_buf[65536 + 128] = {}; // a little larger than `buf`
static char *code_format =
"#include <stdio.h>\n"
"int main() { "
"  unsigned result = %s; "
"  printf(\"%%u\", result); "
"  return 0; "
"}";

static int cur = 0;
static char ops[] = {'+', '-', '*', '/'};
static void gen_num() {
    int num = rand();
    int n = sprintf(buf + cur, "%du", num);
    cur += n;
}

static void gen(char op) {
    buf[cur] = op;
    cur++;
}

static void gen_space(int n) {
    for(int i=0; i<n; i++) {
        buf[cur] = ' ';
        cur++;
    }
}

int choose() {
    // 设置概率 5, 2, 3
    int k = rand() % 10;
    if (k < 5) return 0;
    else if (k < 7) return 1;
    else return 2;
}

static void gen_rand_expr() {
  // 生成随机表达式
  switch (choose()) {
      case 0: gen_space(rand()%3); gen_num(); gen_space(rand()%3); break; // BNF num
      case 1: gen_space(rand()%3); gen('('); gen_rand_expr(); gen(')'); gen_space(rand()%3); break;// BNF (<expr>)
      default: gen_rand_expr(); gen(ops[rand()%4]); gen_rand_expr(); break;// BNF <expr> op <expr>
  }
  buf[cur] = '\0';
}

int main(int argc, char *argv[]) {
  int seed = time(0);
  srand(seed);
  int loop = 1;
  if (argc > 1) {
    sscanf(argv[1], "%d", &loop);
  }
  int i;
  for (i = 0; i < loop; i ++) {
    cur = 0;
    gen_rand_expr();

    sprintf(code_buf, code_format, buf);

    FILE *fp = fopen("/tmp/.code.c", "w");
    assert(fp != NULL);
    fputs(code_buf, fp);
    fclose(fp);

    int ret = system("gcc -Werror=div-by-zero /tmp/.code.c -o /tmp/.expr 2>/dev/null");
    if (ret != 0) continue;

    fp = popen("/tmp/.expr", "r");
    assert(fp != NULL);

    int result;
    ret = fscanf(fp, "%d", &result);
    pclose(fp);

    printf("%u %s\n", result, buf);
  }
  return 0;
}
